﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Modules_Sysmgr_UserAdd : System.Web.UI.Page
{
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_PostHandler postHandler = new Sys_PostManage();
    ISys_RoleHandler roleHandler = new Sys_RoleManage();

    private static string oldPwd = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dataBind();
        }
    }

    private void dataBind()
    {
        FillPost();
        FillStatus();
        FillChkRoleList();

        oldPwd = string.Empty;
        if (Request["ID"] != null && Request["ID"] != string.Empty)
        {

            int _userID = 0;
            int.TryParse(Request["ID"], out _userID);

            if (_userID != 0)
            {
                Sys_UserQuery query = userHandler.GetSys_UserQuery(_userID);
                if (query != null)
                {
                    txtName.Text = query.Name;
                    txtCode.Text = query.Code;
                    txtPwd.Attributes.Add("value", query.Pwd);
                    txtConfimPwd.Attributes.Add("value", query.Pwd);
                    oldPwd = query.Pwd;
                    ddlStatus.SelectedValue = query.Status.ToString();
                    ddlPost.SelectedValue = query.Post_ID.ToString();
                    hdnOrgID.Value = query.Org_ID.ToString();
                    CheckRoles(query.Roles);
                }
            }
        }
    }

    private void FillPost()
    {
        DataTable dtPost = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) });
        ddlPost.DataTextField = "Name";
        ddlPost.DataValueField = "ID";
        ddlPost.DataSource = dtPost;
        ddlPost.DataBind();
    }

    private void FillStatus()
    {
        DataTable dtStatus = new DataTable();
        dtStatus.Columns.Add("Value");
        dtStatus.Columns.Add("Name");
        DataRow drStatus;

        drStatus = dtStatus.NewRow();
        drStatus[0] = "1";
        drStatus[1] = Enums.GetNormalStatusName(Enums.NormalStatus.Vallid);
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "0";
        drStatus[1] = Enums.GetNormalStatusName(Enums.NormalStatus.Invalid);
        dtStatus.Rows.Add(drStatus);

        ddlStatus.DataSource = dtStatus;
        ddlStatus.DataTextField = "Name";
        ddlStatus.DataValueField = "Value";
        ddlStatus.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if ("".Equals(txtCode.Text.Trim()))
        {
            Jscript.Alert("账号不能为空", this.Page);
            return;
        }
        if ("".Equals(txtName.Text.Trim()))
        {
            Jscript.Alert("名称不能为空", this.Page);
            return;
        }
        if ("".Equals(txtPwd.Text.Trim()))
        {
            Jscript.Alert("密码不能为空", this.Page);
            return;
        }
        if (txtPwd.Text != txtConfimPwd.Text)
        {
            Jscript.Alert("两次密码不一致", this.Page);
            return;
        }
        if ("".Equals(hdnOrgID.Value))
        {
            Jscript.Alert("请选择所在部门", this.Page);
            return;
        }

        if (Request["ID"] != null && Request["ID"] != string.Empty)
        {
            if (isCodeExists(txtCode.Text.Trim(), int.Parse(Request["ID"])))
            {
                Jscript.Alert("账号已存在", this.Page);
                return;
            }
        }
        else
        {
            if (isCodeExists(txtCode.Text.Trim()))
            {
                Jscript.Alert("账号已存在", this.Page);
                return;
            }
        }

        Sys_UserQuery query = new Sys_UserQuery();

        if (Request["ID"] != null && Request["ID"] != string.Empty)
        {
            query = userHandler.GetSys_UserQuery(int.Parse(Request["ID"]));
            if (!oldPwd.Equals(txtPwd.Text))
            {
                query.Pwd = DesEncryption.EncryptPassword(txtPwd.Text, "MD5");
            }
        }

        query.Code = txtCode.Text.Trim();
        query.Name = txtName.Text.Trim();
       
        query.Status = int.Parse(ddlStatus.SelectedValue);
        query.Org_ID = int.Parse(hdnOrgID.Value);
        query.Post_ID = int.Parse(ddlPost.SelectedValue);

        if (Request["ID"] == null)
        {
            query.Pwd = DesEncryption.EncryptPassword(txtPwd.Text, "MD5");
        }
        string roleStr = string.Empty;

        for (int i = 0; i < chkRoleList.Items.Count; i++)
        {
            if (chkRoleList.Items[i].Selected)
            {
                roleStr += chkRoleList.Items[i].Value + ",";
            }
        }

        query.Roles = roleStr.TrimEnd(new char[] { ',' });

        if (Request["ID"] != null && Request["ID"] != string.Empty)
        {
            if (userHandler.UpdateSys_User(query))
            {
                Jscript.Alert("更新成功", this.Page);
                Jscript.ReturnAndClose(this.Page, "true");
            }
        }
        else
        {
            if (userHandler.InsertSys_User(query))
            {
                Jscript.Alert("添加成功", this.Page);
                Jscript.ReturnAndClose(this.Page, "true");
            }

        }
    }


    private bool isCodeExists(string code)
    {
        bool istrue = false;

        DataTable dt = userHandler.GetSys_UserList(" Code = @Code", new SqlParameter[] { new SqlParameter("@Code", code) });
        if (dt != null && dt.Rows.Count > 0)
        {
            istrue = true;
        }
        return istrue;
    }

    private bool isCodeExists(string code, int postId)
    {
        bool istrue = false;

        DataTable dt = userHandler.GetSys_UserList("Code=@Code and ID!=@Id", new SqlParameter[] { new SqlParameter("@Code", code), new SqlParameter("@Id", postId.ToString()) });

        if (dt != null && dt.Rows.Count > 0)
        {
            istrue = true;
        }
        return istrue;
    }

    /// <summary>
    /// 初始化角色列表
    /// </summary>
    private void FillChkRoleList()
    {
        DataTable dtRoles = roleHandler.GetSys_RoleList();
        chkRoleList.DataSource = dtRoles;
        chkRoleList.DataTextField = "Name";
        chkRoleList.DataValueField = "ID";
        chkRoleList.DataBind();
    }

    /// <summary>
    /// 初始化选中状态
    /// </summary>
    private void CheckRoles(string roles)
    {
        //初始化选中状态
        for (int i = 0; i < chkRoleList.Items.Count; i++)
        {
            if (roles.Contains(chkRoleList.Items[i].Value))
            {
                chkRoleList.Items[i].Selected = true;
            }

        }
    }
}
